<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2025/2/24
 * 描述:
 */

namespace app\result\chat;

use app\model\chat\ChatConversationsSummary;
use app\model\chat\ChatMessages;
use app\model\user\User;
use app\result\BaseResult;
use app\result\UploadResult;
use GatewayClient\Gateway;

class ChatManagerResult extends BaseResult
{

    //管理员监听
    public function admin_listen_ready(): array
    {
        return self::success_return('success', [
            'socketUrl' => config('worker.socketUrl'),
            'maxReconnectTimes' => config('worker.maxReconnectTimes'),
        ]);
    }

    public function ready($kefu_id, $args = []): array
    {
        if (!empty($args['bsff']) && $args['bsff'] == 'admin_notify') {
            return $this->admin_listen_ready();
        }
        $goods_id = $args['goods_id'] ?? 0;
        $order_sn = $args['order_sn'] ?? '';
        $kefu_ids = [$kefu_id];
        $conversation_id = $args['conversation_id'] ?? 0;
        $targetUser = [
            'id' => $kefu_id,
            'avatar' => 'https://source.alipay168.cn/skushop/d971248a1565ebf807b6454e6f818916.png',
            'nickname' => '平台客服'
        ];
        $data = [
            'socketUrl' => config('worker.socketUrl'),
            'maxReconnectTimes' => config('worker.maxReconnectTimes'),
            'online' => false,
            'kefuAvatar' => 'https://source.alipay168.cn/skushop/d971248a1565ebf807b6454e6f818916.png',
            'kefu_id' => $kefu_id,
            'targetUser' => $targetUser
        ];
        if ($conversation_id) {
            $summary = (new ChatConversationsSummary())->data_get([
                ['conversation_id', '=', $conversation_id],
                ['user_id', 'not in', $kefu_ids]
            ], '*', 'id desc');
            if ($summary) {
                $modelUser = new User();
                try {
                    $isOnline = Gateway::isUidOnline($summary['user_id']);
                } catch (\Exception $e) {
                    $isOnline = false;
                    bs_log($e->getMessage(), 'gateway', 'err-worker.log');
                }
                $data['targetUser'] = [
                    'online' => $isOnline,
                    'id' => $summary['user_id'],
                    'avatar' => $modelUser->where(['user_id' => $summary['user_id']])->value('avatar'),
                    'nickname' => $modelUser->where(['user_id' => $summary['user_id']])->value('username')
                ];
            }
        }
        return self::success_return('success', $data);
    }

    //会话历史记录
    public function history_list($kefu_id, $args = [])
    {
        $kefu_ids = [$kefu_id];
        $conversation_id = $args['conversation_id'] ?? 0;
        if (!$conversation_id) {
            return self::success_return('success', [
                'list' => []
            ]);
        }
        $page = $args['page'] ?? 1;
        $pageSize = $args['limit'] ?? 50;
        $where = [
            'conversation_id' => $conversation_id,
        ];
        $model = new ChatMessages();
        $data = $model->data_list($where, '*', 'id desc', $page, $pageSize)?->toArray();

        //标记已读
        (new ChatConversationsSummary())->data_update([
            'conversation_id' => $conversation_id,
            'user_id' => $kefu_id,
        ], ['read_time' => time(), 'unread_count' => 0,]);

        if ($data) {
            $modelUser = new User();
            $kefuAvatar = 'https://source.alipay168.cn/skushop/d971248a1565ebf807b6454e6f818916.png';
            $defaultAvatar = 'https://source.alipay168.cn/skushop/a14a2eb8bedcc7d07ee58a4440e9e460.png';
            foreach ($data as &$item) {
                $item['type'] = $item['message_type'];
                $item['time'] = ChatResult::format_lastTime($item['created_at']);
                $item['isSelf'] = in_array($item['sender_id'], $kefu_ids);
                $targetUserId = $item['isSelf'] ? $item['receiver_id'] : $item['sender_id'];
                if ($item['isSelf']) {
                    $item['avatar'] = $kefuAvatar;
                } else {
                    $item['avatar'] = $modelUser->where(['user_id' => $targetUserId])->value('avatar') ?? $defaultAvatar;
                }
                $item['file_info'] = null;
                if ($item['type'] == 'file') {
                    $item['file_info'] = UploadResult::get_file_info($item['content']);
                } elseif ($item['type'] == 'goods') {
                    $item['goods_info'] = json_decode($item['content'], true);
                } elseif ($item['type'] == 'order') {
                    $item['order_info'] = json_decode($item['content'], true);
                }
            }
            unset($item);
            //再按id顺序
            usort($data, function ($a, $b) {
                return $a['id'] - $b['id'];
            });
        }
        return self::success_return('success', [
            'list' => $data
        ]);
    }


    //会话列表
    public function conversation_list($kefu_id, $args = []): array
    {
        $kefu_ids = [$kefu_id];
        $page = $args['page'] ?? 1;
        $limit = intval($args['limit'] ?? 10);
        $keyword = $args['keyword'] ?? '';
        $where = [
            ['a.user_id', 'in', $kefu_ids],
            ['a.is_deleted', '=', 0],
        ];

        $field = 'a.user_id,a.conversation_id,a.latest_message_id,a.latest_message_time,a.unread_count as unreadCount';
        $field .= ',b.user_ids';
        $modelSummary = new ChatConversationsSummary();
        $data = $modelSummary->alias('a')
            ->join('chat_conversations b', 'a.conversation_id = b.conversation_id', 'left')
            ->where($where)
            ->page($page, $limit)
            ->order('a.id desc')
            ->field($field)
            ->select()
            ->toArray();
        if ($data) {
            $total = $modelSummary->alias('a')
                ->join('chat_conversations b', 'a.conversation_id = b.conversation_id', 'left')
                ->where($where)
                ->count();
            //相关用户信息
            $user_ids = explode(',', join(',', array_column($data, 'user_ids')));
            $user_ids = array_unique($user_ids);
            $modelUser = new User();
            $modelMessage = new ChatMessages();
            $allUsers = $modelUser->data_list_nopage([['user_id', 'in', $user_ids]], 'user_id,avatar,username,account');
            $allMessages = $modelMessage->data_list_nopage([['id', 'in', array_unique(array_column($data, 'latest_message_id'))]]);
            if ($allUsers) {
                $allUsers = array_column($allUsers, null, 'user_id');
            }
            if ($allMessages) {
                $allMessages = array_column($allMessages, null, 'id');
            }

            $defaultAvatar = 'https://source.alipay168.cn/skushop/a14a2eb8bedcc7d07ee58a4440e9e460.png';
            foreach ($data as &$item) {
                $user_ids = explode(',', $item['user_ids']);
                //移除客服id就是当前用户
                $user_ids = array_diff($user_ids, $kefu_ids);
                sort($user_ids);
                $targetUserId = $user_ids[0] ?? 0;
                $item['targetUserId'] = $targetUserId;
                $item['nickname'] = $allUsers[$targetUserId]['username'] ?? '';
                $item['avatar'] = $allUsers[$targetUserId]['avatar'] ?? $defaultAvatar;
                $message = $allMessages[$item['latest_message_id']];
                $item['lastTime'] = ChatResult::format_lastTime($message['created_at']);
                $item['lastMessage'] = ChatResult::format_lastMessage($message['message_type'], $message['content']);

            }
            unset($item);
        }
        return self::success_return('success', [
            'list' => $data,
            'total' => $total ?? 0,
        ]);
    }

}
